import 'dart:io';

import 'package:bwt_ad_flutter/ad/widget/bannerWidget/BwtBannerWidget.dart';
import 'package:bwt_ad_flutter_example/util/Log.dart';
import 'package:bwt_ad_flutter_example/widget/SimpleWidget.dart';
import 'package:flutter/material.dart';
import 'package:bwt_ad_flutter/ad/loader/BwtBannerAdLoader.dart';

class BannerAdPage extends StatefulWidget {
  const BannerAdPage({super.key});

  @override
  State<BannerAdPage> createState() => _BannerAdPageState();
}

class _BannerAdPageState extends State<BannerAdPage> {
  final BwtBannerAdLoader _bannerAdLoader = BwtBannerAdLoader();

  BwtBannerWidget? _bannerAdView;

  @override
  void initState() {
    super.initState();
    _bannerAdLoader.onAdLoad = (bwtAd) {
      setState(() {
        Log.d("banner加载成功");
        _bannerAdView = bwtAd.bannerAdview;
      });
    };
    _bannerAdLoader.onAdClick = (bwtAd) {
      Log.d("banner广告被点击");
    };

    _bannerAdLoader.onAdFailed = (msg) {
      Log.d("banner加载失败了吗$msg");
    };
    _bannerAdLoader.onAdExpose = (bwtAd) {
      Log.d("banner广告展示成功");
    };
    _bannerAdLoader.onAdClose = (bwtAd) {
      Log.d("banner广告关闭");
    };
  }

  @override
  void dispose() {
    /// 释放广告
    _bannerAdLoader.release();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("banner广告")),
      body: Center(
          child: Column(
        children: [
          SimpleWidget(
            margin: const EdgeInsets.fromLTRB(0, 200, 0, 0),
            alignment: Alignment.center,
            width: 120,
            height: 48,
            decoration: BoxDecoration(
              color: Colors.blue,
              borderRadius: BorderRadius.circular(4),
            ),
            child: const Text(
              '加载banner广告',
              style: TextStyle(
                color: Colors.white,
                fontSize: 16,
              ),
            ),
            onTap: () {
              _loadAd();
            },
          ),
          Visibility(
              key: ValueKey(_bannerAdView?.hashCode),
              child: Container(
                margin: const EdgeInsets.only(top: 50),
                child: _bannerAdView,
              )),
        ],
      )),
    );
  }

  void _loadAd() {
    _bannerAdLoader.loadAd(
        posId: Platform.isAndroid ? "89494998" : "56863448",
        adWidth: 300,
        adHeight: 200,
        showClose: true);
  }
}
